#!/usr/bin/env python
# -*- coding:utf-8 -*-

import traceback
try:
    import jwt
except ImportError:
    print("请安装扩展模块pyjwt!")

def generate_jwt(headers:dict,payload:dict,key:str):
    try:
        jToken = jwt.encode(
            payload=payload,
            key=key,
            algorithm=headers["alg"],
            headers=headers
        )
        return jToken
    except Exception as e:
        return False

def is_dict(cStr:str):
    try:
        result = eval(cStr)
        return result
    except Exception as e:
        return False

def execute(args):
    try:
        headers = input("请输入头信息: ")
        headers = is_dict(headers)
        if headers:
            payload = input("请输入信息载荷部分: ")
            payload = is_dict(payload)
            if payload:
                key = input("请输入密钥: ")
                key = key.strip()
                if key:
                    token = generate_jwt(headers,payload,key)
                    if token:
                        print("结果: " + token)
                    else:
                        print("生成jwt出错!")
                else:
                    print("密钥输入错误!")
            else:
                print("信息载荷输入错误!")
        else:
            print("头信息输入错误!")
    except Exception as e:
        traceback.print_exc()
